package com.zmzncs.lmtc.module.customer.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zmzncs.lmtc.common.pojo.enums.optionalvalue.card.CardTypeEnum;
import com.zmzncs.lmtc.common.util.DateTimeUtil;
import com.zmzncs.lmtc.common.util.WeChatUtil;
import com.zmzncs.lmtc.module.customer.dao.*;
import com.zmzncs.lmtc.module.customer.pojo.car.CarDTO;
import com.zmzncs.lmtc.module.customer.pojo.card.CardDTO;
import com.zmzncs.lmtc.module.customer.pojo.card.CardParkDTO;
import com.zmzncs.lmtc.module.customer.pojo.customer.*;
import com.zmzncs.lmtc.module.customer.service.CustomerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zmzncs.lmtc.module.order.dao.OrderInfoDao;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 客户-客户信息 服务实现类
 * </p>
 *
 * @author 任建波
 * @since 2020-08-26
 */
@Slf4j
@Service
public class CustomerServiceImpl extends ServiceImpl<CustomerDao, Customer> implements CustomerService {

    @Autowired
    HttpServletRequest request;
    @Autowired
    CustomerDao customerDao;
    @Autowired
    CarDao carDao;
    @Autowired
    OrderInfoDao orderInfoDao;
    @Autowired
    CardDao cardDao;
    @Autowired
    CardRecordDao cardRecordDao;
    @Autowired
    CardParkDao cardParkDao;

    /**
     * 获取会员列表
     */
    @Override
    public IPage<CustomerDTO> getCustomerPage(CustomerSearchForm searchForm) {

        String beginTime = searchForm.getBeginTime();
        String endTime = searchForm.getEndTime();
        if (beginTime != null && endTime != null){
            Date begin = DateTimeUtil.fomatDate(beginTime);
            searchForm.setBegin(begin);
            Date end = DateTimeUtil.fomatDate(endTime);
            searchForm.setEnd(end);
        }

        //  查询客户
        IPage<CustomerDTO> customerPage = customerDao.getCustomerList(new Page(searchForm.getCurrentPage(), searchForm.getPageSize()), searchForm);

        //  设置客户车辆
        for(CustomerDTO customerDTO: customerPage.getRecords()){
            //  客户车牌号
            List<CarDTO> carDTOList = carDao.getCustomerCarList(customerDTO.getId());
            List<String> carNumberList = carDTOList.stream().map(CarDTO::getCarNumber).collect(Collectors.toList());
            customerDTO.setCarNumberList(carNumberList);
            //  累计停车时长（分钟）
            Double chargeParkDuration = orderInfoDao.getCustomerChargeParkDuration(customerDTO.getId());
            customerDTO.setChargeParkDuration(chargeParkDuration);
            //  获取客户累计支付金额
            BigDecimal customerPaidAmount = cardRecordDao.getCustomerPaidAmount(customerDTO.getId());
            customerDTO.setPaidAmount(customerPaidAmount);
            //  时长服务余额（分钟）
            Integer durationCardTimeLeft = cardDao.getDurationCardTimeLeft(customerDTO.getId());
            customerDTO.setDurationCardTimeLeft(durationCardTimeLeft);
            //充值余额（元）
            Double recharge = cardDao.getRechargeAmount(customerDTO.getId());
            customerDTO.setRechargeAmount(new BigDecimal(recharge));
        }

        return customerPage;
    }

    /**
     * 会员详情
     */
    @Override
    public CustomerDTO getCustomerInfo(Long id) {
        CustomerDTO customerDTO = customerDao.getCustomerInfo(id);
        return customerDTO;
    }

    /**
     * 查询会员账户
     */
    @Override
    public List<CardDTO> getCustomerAccount(CustomerAccountForm customerAccountForm) {
        List<Integer> cardTypeList = customerAccountForm.getCardTypeList().stream().map(CardTypeEnum::getCode).collect(Collectors.toList());
        //  查询会员卡
        List<CardDTO> cardDTOList = cardDao.getCustomerCardList(customerAccountForm.getId(), cardTypeList);
        for(CardDTO cardDTO: cardDTOList){
            // 月租服务剩余天数
            long diff = cardDTO.getExpireTime().getTime() - new Date().getTime();
            int day = (int) (diff / 24 * 60 * 60 * 1000);
            cardDTO.setMonthCardDaysLeft(day);

            List<CardParkDTO> cardParkDTOList = cardParkDao.getCustomerCarCardParkList(cardDTO.getCustomerId(), cardDTO.getCarId(), cardTypeList);
            List<String> parkNameList = cardParkDTOList.stream().map(CardParkDTO::getParkName).collect(Collectors.toList());
            cardDTO.setParkNameList(parkNameList);
        }

        return cardDTOList;
    }

    /**
     * 获取正式会员和潜在会员数量
     */
    @Override
    public CustomerVipVO getVipCount() {
        Integer vipCount = customerDao.getVipCount(1);
        Integer notVipCount = customerDao.getVipCount(0);

        CustomerVipVO customerVipVO = new CustomerVipVO();
        customerVipVO.setVipCount(vipCount);
        customerVipVO.setNotVipCount(notVipCount);
        return customerVipVO;
    }

    @Override
    public List<CustomerDTO> getCustInfoByPhoneOrName(String info) {
        return customerDao.getCustInfoByPhoneOrName(info);
    }

    @Override
    public Map<String, Object> getAccountDetails(Long customerId) {
        Map<String, Object> map = new HashMap<>();

        //账户余额
        Double rechargeAmount = cardDao.getRechargeAmount(customerId);
        map.put("rechargeAmount",rechargeAmount);

        //累计停车时长
        Double parkDuration = orderInfoDao.getCustomerChargeParkDuration(customerId);
        if(parkDuration.compareTo(0D)!=0){
            map.put("parkDuration",new BigDecimal(Double.valueOf(parkDuration / 60)).setScale(2,   BigDecimal.ROUND_HALF_UP));
        }else{
            map.put("parkDuration",0);
        }


        //累计充值金额
        Double sumRechargeAmount = cardRecordDao.getSumRechargeAmount(customerId);
        map.put("sumRechargeAmount",sumRechargeAmount);

        List<CustomerAccountDetails> carAmount = cardParkDao.getCarAmount(customerId);
        if (carAmount != null && carAmount.size() > 0){
            for (CustomerAccountDetails details : carAmount) {
                Double sumParkDuration = orderInfoDao.getSumParkDuration(details.getCarNum());
                if(sumParkDuration.compareTo(0D)>0){
                    details.setParkDuration(new BigDecimal(Double.valueOf(sumParkDuration / 60)).setScale(2,   BigDecimal.ROUND_HALF_UP));
                }else{
                    details.setParkDuration(BigDecimal.ZERO);
                }

                Date expireTime = details.getExpireTime();
                int days = DateTimeUtil.betweenDays(expireTime, new Date()) + 1;
                details.setMonthDay(days);
            }

        }
        map.put("carAmount",carAmount);

        return map;
    }

    @Override
    public String transfersToUser(String orderCode,String openid, BigDecimal totalFee, String desc) {
        log.info("向用户退款，openid：" + openid);

        Map<String, Object> map = WeChatUtil.transfers(orderCode, openid, totalFee, desc);
        if (map != null && "SUCCESS".equals(map.get("resultCode"))){
            return "向用户付款成功";
        } else {
            return "向用户付款失败";
        }
    }


}
